﻿using Aliyun.MNS;
using Aliyun.MNS.Model;
using Api.Utils;
using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Configuration;
using System.Dynamic;
using System.Text;

namespace Api.Sales.Orders.Messages.MessageQueue
{
    public class AliyunMNS
    {
        private static readonly Lazy<AliyunMNS> lazy =
            new Lazy<AliyunMNS>(() => new AliyunMNS());
        public static AliyunMNS Instance { get { return lazy.Value; } }

        private IMNS MNSClient;
        private const string ACCESS_KEY_ID = "aDrl9HZwhIMHXfse";
        private const string SECRET_ACCESS_KEY = "pMZNUpzMFnNZ3OtQ4mtIndBiHp2nZj";
        private const string REGION_ENDPOINT = "http://1808717019757572.mns.cn-shanghai.aliyuncs.com/";
        private string API_SALES_ORDERS_PRODUCE_QUEUE_NAME = ConfigurationManager.AppSettings["QueueName_SalesOrders"];

        private AliyunMNS()
        {
            this.MNSClient = new MNSClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_ENDPOINT);
        }

        internal void Send(dynamic request, dynamic response)
        {
            try
            {
                string jsonRequest = DynamicConvert.ToJsonString(request);
                byte[] requestBytes = Encoding.UTF8.GetBytes(jsonRequest);
                string base64Request = Convert.ToBase64String(requestBytes);

                var messageRequest = new SendMessageRequest(base64Request);
                var nativeQueue = MNSClient.GetNativeQueue(API_SALES_ORDERS_PRODUCE_QUEUE_NAME);
                var messageResponse = nativeQueue.SendMessage(messageRequest);

                FillResult(response, messageResponse);
            }
            catch (RuntimeBinderException) { }
        }

        private void FillResult(dynamic response, SendMessageResponse sendMessageResponse)
        {
            response.result.message_id = sendMessageResponse.MessageId;
            response.result.message_hash = new ExpandoObject();
            response.result.message_hash.md5 = sendMessageResponse.MessageBodyMD5;
        }

    }
}